<template>
  <el-card
    class="form-container"
    shadow="never"
  >
    <div style="padding:20px">
      <el-steps
        :active="active"
        finish-status="success"
        style="margin-bottom: 20px"
      >
        <el-step title="分类&服务方式"></el-step>
        <el-step title="服务名称"></el-step>
        <el-step title="选择属性规格"></el-step>
        <el-step title="配置库存"></el-step>
      </el-steps>

      <div v-if="active===0">
        <el-form
          :model="rules0"
          ref="rules0"
          label-width="120px"
          style="width: 600px"
          class="select"
        >
          <el-form-item
            label="分类"
            prop="serType"
            :rules="[
              { type: 'array', required: true, message: '分类不能为空', trigger: 'change'}
            ]"
          >
            <el-cascader
              v-model="rules0.serType"
              :options="serTypeList"
              class="input-width"
            ></el-cascader>
          </el-form-item>
          <el-form-item
            label="服务方式"
            prop="prodType"
            :rules="[
              { required: true, message: '请选择服务方式', trigger: 'change' }
            ]"
          >
            <el-radio-group
              v-model="rules0.prodType"
              class="input-width"
            >
              <el-radio
                label="到店"
                value="1"
              ></el-radio>
              <el-radio
                label="上门"
                value="2"
              ></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form
            v-show="rules0.prodType==='上门'"
            label-width="120px"
            style="width: 600px"
            class="select">
            <el-form-item
              label="服务区域："
              required
            >
              <multiple-address
                ref="multipleAddress"
                class="input-width"
              ></multiple-address>
            </el-form-item>
          </el-form>
          <el-form-item
            v-show="rules0.prodType==='到店'"
            label="机构场地"
            prop="siteName"
            :rules="rules0.prodType==='到店'?[
              { required: true, message: '请选择机构场地', trigger: 'change' }
            ]:[]"
          >
            <el-autocomplete
              v-model="rules0.siteName"
              :fetch-suggestions="siteQuerySearchAsync"
              placeholder="请输入内容"
              @select="siteHandleSelect"
              class="input-width"
            ></el-autocomplete>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="active===1">
        <el-form
          :model="rules1"
          ref="rules1"
          label-width="120px"
          style="width: 600px"
          class="select"
        >
          <el-form-item
            label="服务名称"
            prop="prodName"
            :rules="[
              { required: true, message: '请选择服务名称', trigger: 'change' }
            ]"
          >
            <el-autocomplete
              v-model="rules1.prodName"
              :fetch-suggestions="serNameQuerySearchAsync"
              placeholder="请输入内容"
              @select="prodNameSelect"
              class="input-width"
            ></el-autocomplete>
          </el-form-item>

        </el-form>
      </div>
      <div v-if="active===2">
        <el-form
          label-width="120px"
          style="width: 100%"
          class="select"
        >
          <el-card class="box-card">
            <div
              slot="header"
              class="clearfix"
            >
              <span>自然属性</span>
            </div>
            <el-form-item
              v-for="(items,index) in naturePrprtyList"
              :key="index"
              :label="items.prptyNameShow"
            >
              <el-select
                v-model="selectNaturePrprtyList[index]"
                multiple
                placeholder="请选择"
                @change="selectNaturePrprtyChange(items,index)"
              >
                <el-option
                  v-for="item in items.prptyValList"
                  :key="item.value"
                  :label="item.prptyValue"
                  :value="item.prptyValCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-card>
          <el-card
            class="box-card"
            style="margin-top: 20px"
          >
            <div
              slot="header"
              class="clearfix"
            >
              <span>选择规格</span>
            </div>
            <el-table
              :data="skuTableData"
              ref="multipleTable"
              tooltip-effect="dark"
              @selection-change="handleSelectionChange"
              style="width: 100%"
            >
              <el-table-column
                type="selection"
                width="55"
              >
              </el-table-column>
              <el-table-column
                v-for="(item,i) in skuListLabel"
                :key="i"
                :prop="item.prop"
                :label="item.label"
                width="180"
              >
              </el-table-column>
            </el-table>
          </el-card>
        </el-form>
      </div>
      <div v-if="active===3">
        <el-card
          class="box-card"
          style="margin-top: 20px"
        >
          <div
            slot="header"
            class="clearfix"
          >
            <span>库存时间</span>
          </div>

          <el-table
            v-if="rules0.prodType==='到店'"
            :data="stockSkuTableData"
            style="width: 100%"
          >
            <el-table-column
              v-for="(item,i) in stockSkuListLabel"
              :key="i"
              :prop="item.prop"
              :label="item.label"
            >
            </el-table-column>
            <el-table-column
              label="时段1"
              align="center"
            >
              <el-table-column label="服务时段" width="130px">
                <template slot-scope="scope">
                  <el-input
                    v-model="skuInstSaveList[scope.$index].stockArray[0].stockTime"
                    placeholder=""
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="库存" width="80px">
                <template slot-scope="scope">
                  <el-input
                    v-model="skuInstSaveList[scope.$index].stockArray[0].stock"
                    placeholder=""
                  ></el-input>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column
              label="时段2"
              align="center">
              <el-table-column label="服务时段" width="130px">
                <template slot-scope="scope">
                  <el-input
                    v-model="skuInstSaveList[scope.$index].stockArray[1].stockTime"
                    placeholder=""
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="库存" width="80px">
                <template slot-scope="scope">
                  <el-input
                    v-model="skuInstSaveList[scope.$index].stockArray[1].stock"
                    placeholder=""
                  ></el-input>
                </template>
              </el-table-column>
            </el-table-column>

          </el-table>

          <el-table
            v-if="rules0.prodType==='上门'"
            :data="stockSkuTableData"
            style="width: 100%"
          >
            <el-table-column
              v-if="item.prop!=='stock'"
              v-for="(item,i) in stockSkuListLabel"
              :key="i"
              :prop="item.prop"
              :label="item.label"
            >
            </el-table-column>
            <el-table-column label="库存">
              <template slot-scope="scope">
                <el-input
                  v-model="stockSkuTableData[scope.$index].stock"
                  placeholder=""
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

      </div>
      <div style="text-align: center">
        <el-button
          style="margin-top: 30px;width:120px"
          @click="back"
          plain
        >返回列表</el-button>
        <!--<el-button style="margin-top: 30px;width:80px" @click="prevStep" plain v-if="active!==0">返回</el-button>-->
        <el-button
          style="margin-top: 30px;width:80px"
          @click="next(rulesList[active])"
          type="primary"
          v-if="active!==3"
        >下一步</el-button>
        <el-button
          style="margin-top: 30px;width:80px"
          @click="save"
          type="primary"
          v-if="active===3"
        >发布</el-button>
      </div>
    </div>

  </el-card>

</template>

<script>
import {
  productAdd,
  serverspecList,
  siteList,
  getProdSpecById,
  productUpdate,
  getProductById
} from '@/api/deptInst'
// import { province } from '@/api/servDept'
import { prodSpecList, productGetProdStockSetListShow } from '@/api/servMs'
// import SingleAddress from '@/components/SingleAddress'
import MultipleAddress from '@/components/MultipleAddress'

const listToTree = (list, tree, parentId) => {
  list.forEach((item) => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        value: item.id,
        label: item.serverSpecName,
        children: []
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}
export default {
  data () {
    return {
      active: 0,
      rulesList: ['rules0', 'rules1', 'rules2', 'rules3'],
      serTypeList: [],
      rules0: {
        serType: [],
        prodType: '到店',
        siteName: ''
      },
      rules1: {
        prodName: ''
      },
      selectNaturePrprtyList: [],
      // optionsAdress: [],
      naturePrprtyList: [],
      skuTableData: [],
      skuListLabel: [],
      multipleSelection: [],
      stockSkuListLabel: [],
      stockSkuTableData: [],
      skuInstSaveList: [],
      params: {},
      prodViewRes: {}
    }
  },
  components: {
    // SingleAddress,
    MultipleAddress
  },
  created () {
    this.isEdit = this.$route.query.isEdit === 1 || this.$route.query.isEdit === '1' ? 1 : 0
    this.getList()
  },
  mounted () {},
  methods: {
    next (formName) {
      if (this.active === 0) {
        if (this.rules0.prodType === '上门') {
          if (
            this.$refs.multipleAddress.getProdReleaseAreaList().length === 0
          ) {
            this.$message({
              message: '请选择服务区域',
              type: 'error',
              duration: 1000
            })
            return
          } else {
            this.params.prodReleaseAreaList = this.$refs.multipleAddress.getProdReleaseAreaList()
          }
        }
      }
      if (this.active === 1) {
        this.setProdSpec()
      }
      if (this.active === 2) {
        if (this.rules0.prodType === '到店') {
          this.setStockTable()
          this.active++

        }
        if (this.rules0.prodType === '上门') {
          this.getProdStockSetListShow()
        }
      }
      this.$refs[formName] &&
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.active++
          } else {
            return false
          }
        })
    },
    back () {
      this.$router.back()
    },
    prevStep () {
      this.$router.back()
    },
    getProdStockSetListShow () {
      const skuCodes = this.multipleSelection.map((item) => {
        return item.skuCode
      }).toString().replace(/,/g, ';')

      const releaseAreas = []
      this.params.prodReleaseAreaList.map((item) => {
        const { provCode, cityCode, countyCode } = item
        if (provCode) {
          releaseAreas.push(`${provCode}${cityCode ? '_' : ''}${cityCode || ''}${countyCode ? '_' : ''}${countyCode || ''}`)
        }
      })
      // skuCodes=1;3&releaseAreas=110000_110100_110101;110000_110100_110114;130000_130600&prodSpecId=1
      const params = { prodSpecId: this.params.prodSpecId, skuCodes, releaseAreas: releaseAreas.toString().replace(/,/g, ';') }
      if (this.isEdit) {
        params.productId = this.$route.query.prodId
      }

      productGetProdStockSetListShow(params).then((res) => {
        if (res.code === 200) {
          this.stockSkuTableData = res.data.stockSetData
          this.stockSkuListLabel = res.data.stockSetLabel

          if (this.isEdit) {
            this.stockSkuTableData = this.stockSkuTableData.map((items, index) => {
              this.params.skuInstSaveList.map((item, i) => {
                if (index === i) {
                  items.stock = item.stock
                }
              })
              return items
            })
          }
          this.active++
        } else {
          this.$message({
            message: res.message,
            type: 'fail',
            duration: 1000
          })
        }
      })
    },
    setDetail () {
      getProductById({ prodId: this.$route.query.prodId }).then((response) => {
        this.prodViewRes = response.data
        const {
          prodType,
          prodName,
          prodDesc,
          prodSpecId,
          prodTag,
          serverSpecId,
          prptyPackageId,
          skuInstList,
          skuTableDataShow,
          prodChannelList,
          prodPrptyList,
          prodReleaseAreaList
        } = response.data

        this.params.prodName = prodName
        this.params.prodType = prodType
        this.params.prodDesc = prodDesc
        this.params.prodSpecId = prodSpecId
        this.params.prodTag = prodTag
        this.params.serverSpecId = serverSpecId
        this.params.prptyPackageId = prptyPackageId
        this.params.skuInstList = skuInstList
        this.params.skuInstSaveList = skuTableDataShow
        this.params.prodChannelList = prodChannelList
        this.params.naturePrptySaveList = []
        this.params.prodReleaseAreaList = prodReleaseAreaList
        prodPrptyList.map((item) => {
          if (item.prptyType === '2') {
            this.params.naturePrptySaveList.push(item)
          }
        })

        const rules0serType = []
        this.serTypeList.map((items) => {
          if (items.id === serverSpecId) {
            rules0serType.push(serverSpecId)
            return false
          }
          if (items.children && items.children.length > 0) {
            items.children.map((item) => {
              if (item.id === serverSpecId) {
                rules0serType.push(items.id, serverSpecId)
                return false
              }
            })
          }
        })

        //   // 设置初始数据
        this.$set(this.rules0, 'serType', rules0serType)
        this.$set(this.rules0, 'prodType', ['到店', '上门'][prodType - 1])
        this.$set(this.rules0, 'siteName', prodChannelList[0].dealershipName)
        this.$set(this.rules1, 'prodName', prodName)

        this.$refs.multipleAddress.setDefValue(prodReleaseAreaList)

        this.prodSpecId = prodSpecId
      })
    },
    reset () {
      this.serTypeList = []
      this.rules0 = {
        serType: [],
        prodType: '',
        siteId: ''
      }
      this.rules1 = {
        prodName: ''
      }
      this.selectNaturePrprtyList = []
      // this.optionsAdress = []
      this.naturePrprtyList = []
      this.skuTableData = []
      this.skuListLabel = []
      this.multipleSelection = []
      this.stockSkuListLabel = []
      this.stockSkuTableData = []
      this.skuInstSaveList = []
      this.params = {}
      this.prodViewRes = {}
    },
    save () {
      if (this.rules0.prodType === '到店') {
        this.stockSkuTableData.map((item, index) => {
          this.skuInstSaveList[index].skuCode = item.skuCode
        })
      }
      if (this.rules0.prodType === '上门') {
        this.skuInstSaveList = this.stockSkuTableData
        this.prodChannelList = [{
          channelId: this.$route.query.deptId,
          channelName: this.$route.query.deptName
        }]
      }

      const api = [productAdd, productUpdate]

      const params = {
        ...this.params,
        skuInstSaveList: this.skuInstSaveList,
        status: 0
      }
      params.prodServiceTypeList = [
        {
          serviceType: { 到店: '1', 上门: '2' }[this.rules0.prodType],
          serviceTypeName: this.rules0.prodType
        }
      ]
      if (this.isEdit) {
        params.id = this.$route.query.prodId
      }

      if (this.rules0.prodType === '上门') {
        params.prodChannelList = [{
          channelId: this.$route.query.deptId,
          channelName: this.$route.query.deptName
        }]
      }
      api[this.isEdit](params).then((res) => {
        if (res.data === 1 && res.code === 200) {
          this.$message({
            message: '提交成功',
            type: 'success',
            duration: 1000
          })
          this.prevStep()
        } else {
          this.$message({
            message: res.message,
            type: 'fail',
            duration: 1000
          })
        }
      })
    },
    getList () {
      const data = {
        parentId: '',
        isNeedPic: true,
        serverSpecName: '',
        serverSpecLevel: ''
      }
      serverspecList(data).then((response) => {
        listToTree(response.data, this.serTypeList, 0)
        if (this.isEdit) {
          this.setDetail()
        }
      })
    },
    siteQuerySearchAsync (queryString, cb) {
      const params = {
        deptId: this.$route.query.deptId,
        siteName: queryString,
        pageNum: 1,
        pageSize: 10
      }
      siteList(params).then((res) => {
        const results = res.data.list.map((item) => {
          item.value = item.siteName
          return item
        })
        cb(results)
      })
    },
    siteHandleSelect (e) {
      this.params.prodChannelList = [
        {
          channelId: e.deptId,
          channelName: e.deptName,
          dealershipId: e.id,
          dealershipName: e.siteName
        }
      ]
    },
    serNameQuerySearchAsync (queryString, cb) {
      const params = {
        pageNum: 1,
        pageSize: 10,
        prodSpecName: queryString,
        serverSpecId: this.rules0.serType[this.rules0.serType.length - 1]
      }
      prodSpecList(params).then((res) => {
        const results = res.data.list.map((item) => {
          item.value = item.specName
          return item
        })
        cb(results)
      })
    },
    prodNameSelect (e) {
      this.prodSpecId = e.id
      this.rules1.prodName = e.specName

      this.params.prodName = e.specName
      this.params.prodType = { 到店: '1', 上门: '2' }[this.rules0.prodType]
      this.params.prodDesc = e.specDesc
      this.params.prodSpecId = e.id
      this.params.prodTag = e.specTag
      this.params.serverSpecId = e.serverSpecId
      this.params.prptyPackageId = e.prptyPackageId
    },
    selectNaturePrprtyChange (items, index) {
      this.params.naturePrptySaveList[index] = {
        prptyCode: items.prptyCode,
        prptyValCode: this.selectNaturePrprtyList[index].toString()
      }
    },
    setProdSpec () {
      const params = {
        prodSpecId: this.prodSpecId
      }
      getProdSpecById(params).then((res) => {
        if (!this.isEdit) this.params.naturePrptySaveList = []

        const { prprtyPackage, skuListLabel, skuTableData } = res.data

        prprtyPackage.prptyList.map((item, index) => {
          if (item.prptyType === '2') {
            this.naturePrprtyList.push(item)
            this.selectNaturePrprtyList.push([])
            if (!this.isEdit) this.params.naturePrptySaveList.push({})
          }
        })

        this.skuListLabel = skuListLabel
        this.skuTableData = skuTableData
        if (this.isEdit) {
          this.params.naturePrptySaveList.map((item, index) => {
            item.prodPrptyValList.map((i) => {
              this.selectNaturePrprtyList[index].push(i.prptyValCode)
            })
          })
          this.params.skuInstList.map((items) => {
            skuTableData.map((item) => {
              if (items.code === item.skuCode) {
                this.multipleSelection.push(item)
              }
            })
          })

          // this.params.skuInstSaveList.map((items) => {
          //   skuTableData.map((item) => {
          //     if (items.skuCode === item.skuCode) {
          //       this.multipleSelection.push(item)
          //     }
          //   })
          // })

          const o = this
          setTimeout(() => {
            this.multipleSelection.map((item) => {
              o.$refs.multipleTable.toggleRowSelection(item)
            })
          }, 100)
        }
      })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    setStockTable () {
      this.stockSkuListLabel = this.skuListLabel
      this.stockSkuTableData = this.multipleSelection
      if (this.isEdit) {
        let skuCodeList = []
        this.params.skuInstSaveList.map((item) => {
          skuCodeList.push(item.skuCode)
        })
        skuCodeList = Array.from(new Set(skuCodeList))
        const list = skuCodeList.map((item) => {
          return {
            skuCode: item,
            stockArray: []
          }
        })
        this.skuInstSaveList = list.map((items) => {
          this.params.skuInstSaveList.map((item) => {
            const { skuCode, stockTime, stock } = item
            if (items.skuCode === skuCode) {
              items.stockArray.push({
                stockTime,
                stock
              })
            }
          })
          return items
        })
      } else {
        this.stockSkuTableData.map(() => {
          this.skuInstSaveList.push({
            skuCode: '',
            stockArray: [
              {
                stockTime: '',
                stock: 0
              },
              {
                stockTime: '',
                stock: 0
              }
            ]
          })
        })
      }
    }
  }
}
</script>
<style scoped>
.box-card {
  width: 100%;
}
.form-container {
  width: 800px;
}
.input-width {
  width: 70%;
}
</style>
